package com.zifeng.study.springbootshirojwtdemo.controller;

import com.zifeng.study.springbootshirojwtdemo.bean.User;
import com.zifeng.study.springbootshirojwtdemo.mapper.UserMapper;
import com.zifeng.study.springbootshirojwtdemo.reponse.Response;
import com.zifeng.study.springbootshirojwtdemo.utils.JwtUtil;
import com.zifeng.study.springbootshirojwtdemo.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 吴梓锋
 * @date: 2022/01/14 15:10:42
 * @version: 1.0.0
 * @description: 测试shiro功能controller
 */
@RestController
@RequestMapping(("/shiro"))
@Slf4j
public class TestShiroController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    HttpServletRequest request;

    @PostMapping("/login")
    public Response login(@Validated @RequestBody User user) {
        User user2 = userMapper.getUserByUserName(user.getUserName());

        // 用户不存在
        if (ObjectUtils.isEmpty(user2)) {
            return ResponseUtil.error("400", "登陆失败!", "用户不存在!");
        }

        // 密码校验。这里为了方便直接用明文
        if (verifyPassword(user.getPassword(), user2.getPassword())) {
            // 签发token
            String token = JwtUtil.createToken(user2.getId() + "", user2.getUserName());
            log.info("用户:{}登陆成功，token为:{}", user.getUserName(), token);

            return ResponseUtil.success("登陆成功!", token);
        } else {
            return ResponseUtil.error("401", "登陆失败!", "密码校验错误！");
        }
    }

    @GetMapping("/getMessageWithPermission")
    @RequiresPermissions("vip")
    public Response getMessageWithPermission() {
        // 获取Token
        String token = request.getHeader("Token");
        // 获取用户Id
        int userId = Integer.parseInt(JwtUtil.getAudience(token));
        // 获取用户信息
        User user = userMapper.getUserByUserId(userId);
        return ResponseUtil.success(user);
    }

    @GetMapping("/getMessageWithRole")
    @RequiresRoles("admin")
    public Response getMessageWithRole() {
        // 获取Token
        String token = request.getHeader("Token");
        // 获取用户Id
        int userId = Integer.parseInt(JwtUtil.getAudience(token));
        // 获取用户信息
        User user = userMapper.getUserByUserId(userId);
        return ResponseUtil.success(user);
    }

    private boolean verifyPassword(String password, String password1) {
        // 假如不是明文可以在这里扩展
        return password.equals(password1);
    }

}
